package translinkApp.Activities;

import translinkApp.Activities.BillingService.RequestPurchase;
import translinkApp.Activities.BillingService.RestoreTransactions;
import translinkApp.DialogBoxes.GoCard.GoCardDetailsDialog;
import translinkApp.DialogBoxes.GoCard.GoCardDetailsDialogData;
import translinkApp.Donations.Consts.PurchaseState;
import translinkApp.Donations.Consts.ResponseCode;
import translinkApp.Donations.PurchaseObserver;
import translinkApp.Donations.ResponseHandler;
import translinkApp.Utilities.DataResource;
import translinkApp.Utilities.Utils;
import translinkApp.views.activity.DialogGenerator;
import translinkApp.views.activity.DialogGeneratorList;
import translinkApp.views.activity.DialogLoaderActivityHelper;
import translinkApp.views.activity.DialogLoaderActivityInf;
import translinkApp.views.dialog.LachDialog;
import translinkApp.views.dialog.LachDialogArguments;
import translinkApp.views.dialog.LachDialogData;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements DialogLoaderActivityInf {

	private final int LOCATION_DIALOG_ID = 0;
	/**
	 * The SharedPreferences key for recording whether we initialized the database. If false, then
	 * we perform a RestoreTransactions request to get all the purchases for this user.
	 */
	private TranslinkPurchaseObserver mTranslinkPurchaseObserver;
	private Handler mHandler;

	private BillingService mBillingService;

	/**
	 * The developer payload that is sent with subsequent purchase requests.
	 */
	private String mPayloadContents = null;

	private static final int DIALOG_CANNOT_CONNECT_ID = 1;
	private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;

	/**
	 * Each product in the catalog is either MANAGED or UNMANAGED. MANAGED means that the product
	 * can be purchased only once per user (such as a new level in a game). The purchase is
	 * remembered by Android Market and can be restored if this application is uninstalled and then
	 * re-installed. UNMANAGED is used for products that can be used up and purchased multiple times
	 * (such as poker chips). It is up to the application to keep track of UNMANAGED products for
	 * the user.
	 */
	private enum Managed {
		MANAGED, UNMANAGED
	}

	/**
	 * A {@link PurchaseObserver} is used to get callbacks when Android Market sends messages to
	 * this application so that we can update the UI.
	 */
	private class TranslinkPurchaseObserver extends translinkApp.Donations.PurchaseObserver {

		public TranslinkPurchaseObserver(Handler handler) {
			super(SettingsActivity.this, handler);
		}

		@Override
		public void onBillingSupported(boolean supported) {

			if (!supported) {
				showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
			}
		}

		@Override
		public void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity,
				long purchaseTime, String developerPayload) {

			if (purchaseState == PurchaseState.PURCHASED) {
				if (itemId.equals(proVersion.sku)) {
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
					Editor edit = prefs.edit();
					edit.putBoolean("proversion", true);
					edit.commit();
					
					Utils.showDialog(SettingsActivity.this, "Pro version purchased!");
					
				} else {

					Utils.showDialog(SettingsActivity.this, "Could not match the sku");
				}
			}

		}

		@Override
		public void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode) {

		}

		@Override
		public void onRestoreTransactionsResponse(RestoreTransactions request,
				ResponseCode responseCode) {

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_CANNOT_CONNECT_ID:
			return createDialog(R.string.cannot_connect_title, R.string.cannot_connect_message);
		case DIALOG_BILLING_NOT_SUPPORTED_ID:
			return createDialog(R.string.billing_not_supported_title,
					R.string.billing_not_supported_message);
		default:
			return null;
		}
	}

	private Dialog createDialog(int titleId, int messageId) {
		String helpUrl = getString(R.string.help_url);
		final Uri helpUri = Uri.parse(helpUrl);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(titleId).setIcon(android.R.drawable.stat_sys_warning)
				.setMessage(messageId).setCancelable(false)
				.setPositiveButton(android.R.string.ok, null)
				.setNegativeButton(R.string.learn_more, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(Intent.ACTION_VIEW, helpUri);
						startActivity(intent);
					}
				});
		return builder.create();
	}

	private static class CatalogEntry {
		public String sku;
		public int nameId;
		private Managed managed;

		public CatalogEntry(String sku, int nameId, Managed managed) {
			this.sku = sku;
			this.nameId = nameId;
			this.managed = managed;
		}
	}

//	CatalogEntry proVersion = new CatalogEntry("proversion", R.string.proversion, Managed.MANAGED);
	CatalogEntry proVersion = new CatalogEntry("android.test.purchased", R.string.proversion, Managed.MANAGED);

	private Preference getPreference(int resID) {
		return (Preference) getPreferenceScreen().findPreference(getString(resID));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.menu);

		Preference locationsPreference = getPreference(R.string.Locations_Preference_Menu);
		Intent locationList = new Intent(this, LocationsMenuActivity.class);
		locationsPreference.setIntent(locationList);

		Preference journeysPreference = getPreference(R.string.Journeys_Preference_Menu);
		Intent favouritesList = new Intent(this, FavouritesMenuActivity.class);
		journeysPreference.setIntent(favouritesList);

		Preference clearHistoryPreference = getPreference(R.string.Clear_History_Menu);
		clearHistoryPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				clearHistory();
				return true;
			}
		});

		Preference gocardPreference = getPreference(R.string.Go_Card_Preference_Menu);
		gocardPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				showLachDialog(LOCATION_DIALOG_ID, null);
				return true;
			}
		});

		Preference donatePreference = getPreference(R.string.Donate_Preference_Menu);
		donatePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {

				mHandler = new Handler();
				mTranslinkPurchaseObserver = new TranslinkPurchaseObserver(mHandler);
				mBillingService = new BillingService();
				mBillingService.setContext(SettingsActivity.this);

				ResponseHandler.register(mTranslinkPurchaseObserver);

				// Check if billing is supported.
				if (!mBillingService.checkBillingSupported()) {
					showDialog(DIALOG_CANNOT_CONNECT_ID);
					return true;
				}

				if (!mBillingService.requestPurchase(proVersion.sku, mPayloadContents)) {
					showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
				}

				ResponseHandler.unregister(mTranslinkPurchaseObserver);
				mBillingService.unbind();

				return true;
			}
		});
	}

	private void clearHistory() {
		AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
		builder.setMessage("Are you sure you want to clear the history?").setCancelable(true);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

				DataResource.journeysHistoryList.getData().clear();
				DataResource.journeysHistoryList.save(SettingsActivity.this);

				Toast.makeText(SettingsActivity.this, "History cleared", Toast.LENGTH_SHORT).show();
			}
		});
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		builder.create().show();
	}

	@Override
	public void dialogGenerator(DialogGeneratorList list) {
		list.addDialog(new DialogGenerator() {

			@Override
			public LachDialog createDialog(LachDialogArguments args, LachDialogData data) {

				final GoCardDetailsDialog goCardDialog = new GoCardDetailsDialog(
						SettingsActivity.this, args, (GoCardDetailsDialogData) data);

				return goCardDialog;
			}
		});
	}

	@Override
	public void showLachDialog(int number, LachDialogArguments args) {
		getDialogHelper().showLachDialog(number, args);
	}

	@Override
	public void showLachDialog(int number, LachDialogArguments args, LachDialogData data) {
		getDialogHelper().showLachDialog(number, args, data);

	}

	@Override
	public void recreateDialog(Bundle savedInstanceState) {
		getDialogHelper().recreateDialog(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		getDialogHelper().onSaveInstanceState(outState);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		getDialogHelper().onActivityResult(requestCode, resultCode, data);
	}

	DialogLoaderActivityHelper impl;

	public DialogLoaderActivityHelper getDialogHelper() {
		if (impl == null) {
			impl = new DialogLoaderActivityHelper(this);
		}
		return impl;
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		recreateDialog(savedInstanceState);

	}

}
